﻿using UnityEngine;
using System.Collections;
using System;

public class CameraRenderToTexture :MonoBehaviour
{
    public Shader shader;
    //public Shader shaderForPlane;
    public MeshRenderer meshRenderer;
    private Material material;
    private RenderTexture tmpRt;
    private Camera cam;


    void Start()
    {
        tmpRt = new RenderTexture( 1024, 1024, 0 );
        tmpRt.useMipMap = false;
        tmpRt.wrapMode = TextureWrapMode.Clamp;
        tmpRt.format = RenderTextureFormat.ARGB32;
        tmpRt.filterMode = FilterMode.Point;
        tmpRt.hideFlags = HideFlags.HideAndDontSave;
        tmpRt.name = "Shadow Texture";

        cam = GetComponent<Camera>();
        
        cam.targetTexture = tmpRt;
        cam.aspect = 1;
        //cam.SetReplacementShader( shader, "RenderType" );

        //cam.nearClipPlane = 0.01f;
        //cam.farClipPlane = 99f;
        cam.renderingPath = RenderingPath.VertexLit;
        cam.SetReplacementShader( shader, "" );

        Color c = Color.white;
        c.a = 0f;
        cam.backgroundColor = c;
         

        //material = new Material( shaderForPlane );
        //material.name = "Render Shadow";
        //meshRenderer.materials[0] = material;
        // 
        
        meshRenderer.materials[0].SetTexture( "_MainTex", tmpRt );
    }
    void OnDestroy()
    {
        if(tmpRt != null)
        {
            tmpRt.Release();
            Destroy(tmpRt);
            tmpRt = null;
        }
        
    }
}
